package com.gui.controller;

import com.gui.DTO.GiteeOAuther;
import com.gui.DTO.GiteeUser;
import com.gui.DTO.LimitDTO;
import com.gui.exception.DIYExceptionHandler;
import com.gui.model.User;
import com.gui.provider.GiteeProvider;
import com.gui.service.LimitPageSevice;
import com.gui.service.LoginService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * LoginController
 *
 * @author guigu
 * @QQ 1170258867
 * @date 2020/5/26
 * @description gitee验证登录
 */
@Controller
public class LoginController {

    @Autowired
    private GiteeOAuther giteeOAuther;
    @Autowired
    private GiteeProvider giteeProvider;
    @Autowired
    private LoginService loginService;
    @Autowired
    private LimitPageSevice limitPageSevice;

    @RequestMapping("/callback")
    public String callback(@RequestParam("code") String code, HttpServletResponse response) throws DIYExceptionHandler {
        giteeOAuther.setCode(code);
        String token = giteeProvider.getaccessToken(giteeOAuther);
        GiteeUser giteeUser = giteeProvider.getUserJson(token);
        if (giteeUser != null) {
            UUID tokenuuid = UUID.randomUUID();
            User user = new User(giteeUser.getId(), giteeUser.getName(), tokenuuid.toString(), giteeUser.getAvatarUrl());
            response.addCookie(new Cookie("token", tokenuuid.toString()));
            loginService.saveOrUpdate(user);
        }
        return "redirect:/";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response, Model model){
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token",null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        LimitDTO limitDTO = limitPageSevice.Bulider(new LimitDTO(), 1);
        model.addAttribute("limitDTO",limitDTO);
        return "main";
    }

}
